<!DOCTYPE html>
<html>

<head>
  <!-- USE DEVELOPMENT VERSION -->
  <script src="/konva.min.js"></script>
  <meta charset="utf-8" />
  <title>Konva 矩形图形变换 </title>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #f0f0f0;
    }
  </style>
</head>

<body>
  <div id="container"></div>
  <script>
    var width = window.innerWidth
    var height = window.innerHeight

    var stage = new Konva.Stage({
      container: 'container',
      width: width,
      height: height
    })

    var layer = new Konva.Layer()
    stage.add(layer)

    var rect = new Konva.Rect({
      name: 'rect-1',
      x: 200,
      y: 150,
      width: 100,
      height: 100,
      fill: 'red',
      name: 'rect',
      stroke: 'black',
      draggable: true
    })
    layer.add(rect)

    var text = new Konva.Text({
      name: 'text-1',
      x: 5,
      y: 5
    })
    layer.add(text)
    updateText()

    //  创建变换器
    var tr = new Konva.Transformer()
    layer.add(tr)
    // 追加到矩形
    tr.attachTo(rect)
    layer.draw()

    // 监听开始变换
    rect.on('transformstart', function () {
      console.log('开始变换')
    })

    rect.on('dragmove', function () {
      console.log('移动中')
      updateText()
    })
    rect.on('transform', function () {
      console.log('变换中')
      updateText()
    })

    rect.on('transformend', function () {
      console.log('变换结束')
    })

    function updateText () {
      var lines = [
        'x: ' + rect.x(),
        'y: ' + rect.y(),
        'rotation: ' + rect.rotation(),
        'width: ' + rect.width(),
        'height: ' + rect.height(),
        'scaleX: ' + rect.scaleX(),
        'scaleY: ' + rect.scaleY()
      ]
      text.text(lines.join('\n'))
      layer.batchDraw()
    }
  </script>
</body>

</html>